import type {WeatherData, GetWeatherRequest} from './domain';
import {WeatherHandler} from '@/modules/application/utils/proxyBackendUtils/handlers/weatherHandler';
import {AppBackendService, AppBackendServiceError} from "@/shared/api/appBackendService";
import {HttpService} from "@/shared/api/httpService";

class WeatherService extends HttpService {
    private weatherHandler: WeatherHandler | null = null;

    constructor() {
        // super('/api/backend');
        super(`https://api.weatherapi.com`);
    }

    private urls = {
        weather: '/weather',
        weather2: '/v1/current.json',
    };

    getWeather = async (params: GetWeatherRequest): Promise<WeatherData> => {
        // On client side, make HTTP request as before
        try {
            const result = await this.request<WeatherData>(this.urls.weather, {queryParams: params}, {method: 'GET'});
            return result;
        } catch (error) {
            console.error('Weather service error:', error);
            // Fallback to mock data if the API fails
            return this.getMockWeatherData(params.city);
        }
    };

    getWeather2 = async (params: GetWeatherRequest): Promise<WeatherData> => {
        // On client side, make HTTP request as before
        const params2 = {q: params.city,key: 'ec28d6edb25a4169b7120833252309'};
        try {
            const rawData = await this.request<any>(this.urls.weather2, { queryParams: params2 }, { method: 'GET' });
            // 转换为 WeatherData 结构
            return {
                location: rawData.location.name,
                temp_c: rawData.current.temp_c,
                condition: rawData.current.condition.text,
            };
        } catch (error) {
            console.error('Weather service error:', error);
            // Fallback to mock data if the API fails
            return this.getMockWeatherData(params.city);
        }
    };

    private getMockWeatherData = (city: string): WeatherData => {
        // Provide mock data as fallback
        const mockData: Record<string, WeatherData> = {
            '河南漯河': {
                location: '河南漯河 (模拟数据)',
                temp_c: 25,
                condition: '晴天'
            },
            'Beijing': {
                location: 'Beijing (Mock)',
                temp_c: 22,
                condition: 'Partly Cloudy'
            }
        };

        return mockData[city] || {
            location: `${city} (模拟数据)`,
            temp_c: 20,
            condition: '数据不可用'
        };
    };
}

export const weatherService = new WeatherService();
// Also export the class and instance for backward compatibility
export {WeatherService};
